package gao.xiaolei.controller;

import gao.xiaolei.entity.User;
import org.springframework.web.bind.annotation.*;
import gao.xiaolei.dto.JwtDto;
import gao.xiaolei.util.JwtUtil;
import gao.xiaolei.dto.UserRealNameDto;
import gao.xiaolei.service.AuthService;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
public class AuthController {

    @Resource(name = "AuthService")
    private AuthService authService;

    @PostMapping("/login")
    public JwtDto userLogin(@RequestParam(name = "userName") String userName,
                            @RequestParam(name = "password") String password,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        JwtDto result = authService.userLoginProcess(userName, password);
        if (result.getCode() == 200) {
            Cookie cookie = new Cookie("access_token", result.getToken());
            cookie.setMaxAge(24 * 60 * 60 * 1000);
            cookie.setPath("/");//设置作用域,如果不设置cookie的path就是/user,那么去请求/user的父亲和兄弟路径就不会带上该cookie
            response.addCookie(cookie);
        }
        return result;
    }

    @PostMapping("/register")
    public Integer register(@RequestParam(name = "id") String id,
                            @RequestParam(name = "userName") String userName,
                            @RequestParam(name = "realName") String realName,
                            @RequestParam(name = "password") String password) {
        return authService.userRegister(id, userName, realName, password);

    }

    @GetMapping("/refresh/{userId}")
    public JwtDto refreshToken(@PathVariable(name = "userId") String userId) {
        return authService.refreshToken(userId);
    }

    @GetMapping("/branch/{access_token}")
    public List<User> getBranch(@PathVariable(name = "access_token") String access_token) {
        return authService.getBranch(access_token);
    }

    @GetMapping("/branchGroup/{access_token}")
    public String getBranchGroup(@PathVariable(name = "access_token") String access_token) {
        return authService.getBranchGroup(access_token);
    }

}
